package com.briup.ch12;

/**
 * @author yuxi
 * @version 1.0
 * @date 2025/10/20
 * @Description:
 */
import java.io.*;
import java.net.*;
import java.util.*;

public class ChatServer {
    // 存储所有客户端输出流（线程安全）
    private static List<PrintWriter> clients = Collections.synchronizedList(new ArrayList<>());

    public static void main(String[] args) throws IOException {
        ServerSocket server = new ServerSocket(8888);
        System.out.println("聊天室服务器启动，端口8888");

        while (true) {
            // 接受客户端连接
            Socket socket = server.accept();
            new Thread(() -> {
                try (
                        BufferedReader in = new BufferedReader(
                                new InputStreamReader(socket.getInputStream()));
                        PrintWriter out = new PrintWriter(socket.getOutputStream(), true)
                ) {
                    // 读取用户名
                    String name = in.readLine();
                    clients.add(out);
                    broadcast("系统：" + name + "进入聊天室"); // 广播进入消息

                    // 循环接收消息并广播
                    String msg;
                    while ((msg = in.readLine()) != null) {
                        if ("exit".equals(msg)) break; // 退出指令
                        broadcast(name + "：" + msg);
                    }

                    // 处理退出
                    clients.remove(out);
                    broadcast("系统：" + name + "离开聊天室");
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }).start();
        }
    }

    // 广播消息给所有客户端
    private static void broadcast(String msg) {
        for (PrintWriter out : clients) {
            out.println(msg);
        }
    }
}
